package Main;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.print.Doc;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class DbToExcel {

    static MongoClient mongoClient = new MongoClient("192.168.1.173", 27017);
    static MongoDatabase mDatabase = mongoClient.getDatabase("巨潮网络");
    static MongoCollection collection = mDatabase.getCollection("Check_沪市");
    static Logger logger = LoggerFactory.getLogger(DbToExcel.class);
    static final String SAVEPATH = "D:\\测试临时文件\\"+collection.getNamespace().getCollectionName()+"\\";

    public static void main(String[] args) throws IOException, InterruptedException {
        int excelIndex = 0;
        boolean flag = true;
        int lastDoc_id = 0;
        Document query = null;
        initFolder(SAVEPATH);

        int index = 0;
        while (flag){
            if (excelIndex != 0)
                query = new Document("_id",new Document("$gt",lastDoc_id));
            else
                query = new Document();

            //FindIterable<Document> documents = collection.find(query).limit(500000);
            FindIterable<Document> documents = collection.find().skip(index).limit(500000);
            index += 500000;


            if (documents.first() == null){
                flag = false;
                continue;
            }

            lastDoc_id = WriteToExcel(documents, collection.getNamespace().getCollectionName()+ "_" + excelIndex++ + ".xlsx");
        }


    }

    public static void initFolder(String folderPath){
        /**
         * 检查folderPath是否存在
         * 若不存在，创建相关文件夹
         */
        File folder = new File(folderPath);

        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
            System.out.println("创建文件夹");
        } else {
            System.out.println("文件夹已存在");
        }
    }


    public static int WriteToExcel(FindIterable<Document> documents, String excelName) throws IOException {
        logger.info(excelName + " 开始写入");

        List<Document> dataList = new ArrayList<>();
        for (Document document : documents)
            dataList.add(document);

        Set<String> firstLine = new LinkedHashSet<>();
        for (Document document : dataList){
//            for (String key : document.keySet())
//              firstLine.add(key.trim());
            firstLine.addAll(document.keySet());
        }
        //firstLine.addAll(documents.first().keySet());

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        /**
         * 第一行
         */
        Row firstRow = sheet.createRow(0);
        int index = 0;
        int n = firstLine.size();
        for (String key : firstLine)
            firstRow.createCell(index++).setCellValue(key);


        Document returnDoc = null;
        int rownum = 1;
        int count = 0;
        for (Document document : dataList) {
            int cellnum = 0;

            count++;
            Row row = sheet.createRow(rownum++);
            for (String key : firstLine){
                try {
                    row.createCell(cellnum).setCellValue(document.get(key).toString());
                }
                catch (Exception e){
                    row.createCell(cellnum).setCellValue("");
                }
                finally {
                    cellnum++;
                }

            }

            System.out.println("正在写入------------------------------");
            returnDoc = document;
        }

        workbook.write(new FileOutputStream(SAVEPATH+excelName));
        logger.info("写入excel完毕*--------------------\n条目数量："+ count + "\n导出路径："+ SAVEPATH);
        //return returnDoc.getInteger("_id");
        return 0;
    }
}

